import { userInfoType, loginQueryInt } from '@/types/user'
import { defineStore } from 'pinia'
import { piniaPersistConfig } from '../index'
import { getUserInfo, postLogin } from '@/apis/user'
type stateType = {
  token: string
  userInfo: userInfoType
  username: string
  avatar: string
}
const useUserStore = defineStore('user', {
  state: (): stateType => {
    return {
      // token密钥
      token: '',
      // 用户信息
      userInfo: {} as userInfoType,
      username: '',
      avatar: ''
    }
  },
  actions: {
    setToken(payload: string) {
      this.token = payload
      console.log(this.token)
    },
    setUserInfo(payload: userInfoType) {
      this.userInfo = payload
    },
    // 登录
    async postLoginAction(formObj: loginQueryInt) {
      try {
        const res = await postLogin(formObj)
        if (res.code === 200) {
          this.token = res.data?.token
          await this.getUserInfoAction(res.data?.token)
          ElNotification({
            message: '登录成功',
            type: 'success'
          })

          return 'ok'
        } else {
          return Promise.reject(res)
        }
      } catch (error) {
        console.error('请求出错', error)
        return Promise.reject(error)
      }
    },
    // 获取用户信息
    async getUserInfoAction(token: string) {
      const res = await getUserInfo(token)
      this.userInfo = res.data
      this.username = res.data?.username
      return 'ok'
    },
    // 退出登录
    postLogoutAction() {
      localStorage.removeItem('user')
      this.token = ''
      this.username = ''
      this.userInfo = {} as userInfoType
    }
  },
  // 状态持久化
  persist: piniaPersistConfig('user', ['token', 'userInfo'])
})
export default useUserStore
